<template>
  <div class="slider-container">
    <div class="slider-track" ref="trackRef">
      <div 
        class="slider-thumb"
        @mousedown="startDrag"
        :style="{ left: thumbPosition + 'px' }"
      >→</div>
      <div class="slider-hint">{{ isVerified ? '✓ 验证成功' : '向右拖动滑块' }}</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'

const trackRef = ref()
const thumbPosition = ref(0)
const isVerified = ref(false)
const maxPosition = ref(0)

onMounted(() => {
  maxPosition.value = trackRef.value.offsetWidth - 40 // 40是滑块宽度
})

const startDrag = (e  : any) => {
  e.preventDefault()
  const moveHandler = (moveEvent: MouseEvent) => {
    const newPos = Math.min(
      maxPosition.value,
      Math.max(0, moveEvent.clientX - e.target.offsetWidth/2 - trackRef.value.getBoundingClientRect().left)
    )
    thumbPosition.value = newPos
    if (newPos >= maxPosition.value - 5) {
      isVerified.value = true
      document.removeEventListener('mousemove', moveHandler)
    }
  }
  document.addEventListener('mousemove', moveHandler)
  document.addEventListener('mouseup', () => {
    document.removeEventListener('mousemove', moveHandler)
    if (!isVerified.value) thumbPosition.value = 0 // 未完成则复位
  }, { once: true })
}
</script>

<style scoped>
.slider-container {
  width: 310px;
  margin: 20px auto;
}
.slider-track {
  height: 40px;
  background: #f0f3f7;
  border-radius: 20px;
  position: relative;
}
.slider-thumb {
  width: 40px;
  height: 40px;
  background: #409eff;
  border-radius: 20px;
  position: absolute;
  top: 0;
  left: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: bold;
  cursor: grab;
  user-select: none;
}
.slider-hint {
  position: absolute;
  width: 100%;
  text-align: center;
  line-height: 40px;
  color: #666;
  pointer-events: none;
}
</style>